package com.free.semantic.common;

import com.google.common.collect.Lists;

import java.util.List;


public class ParamNode implements BaseNode {

    private Range range;

    private String nodeName;

    private Object value;

    /**
     * 反序列化的时候有用
     */
    public ParamNode() {
    }

    public ParamNode(String nodeName) {
        this.nodeName = nodeName;
    }

    public ParamNode(RangeObj range) {
        this.nodeName = range.getObjectName();
        this.range = range.getRange();
    }

    public ParamNode(Range range, String nodeName) {
        this.range = range;
        this.nodeName = nodeName;
    }

    public ParamNode(RangeObj range, Object value) {
        this.value = value;
        this.nodeName = range.getObjectName();
        this.range = range.getRange();
    }

    @Deprecated
    public ParamNode(String nodeName, Object value) {
        this.value = value;
        this.nodeName = nodeName;
    }

    public static ParamNode parse(String info) {
        info = info.trim();
        if (!info.startsWith("(") || !info.endsWith(")")) {
            throw new IllegalArgumentException();
        }
        String substring = info.substring(1, info.length() - 1);
        int index = substring.indexOf(",");
        String obj = substring.substring(0, index).trim();
        String val = substring.substring(index + 1);
        return new ParamNode(obj, val);
    }

    /**
     * todo 此处对于 range是 多 的数据处理有问题
     *
     * @param <T>
     * @return
     */
    public <T> List<T> value() {
        if (value == null) {
            throw new IllegalArgumentException(String.format("类型 %s 的值为空", nodeName));
        }
        if (value instanceof List) {
            return (List<T>) value;
        }
        return (List<T>) Lists.newArrayList(value);
    }

    @Override
    public String getNodeName() {
        return nodeName;
    }

    public void setNodeName(String nodeName) {
        this.nodeName = nodeName;
    }

    @Override
    public Range getRange() {
        return range;
    }

    @Override
    public String toString() {
        if (value == null) {
            return String.format("(%s,)", nodeName);
        } else {
            return String.format("(%s,%s)", nodeName, value);
        }
    }

    public Object getValue() {
        return value;
    }

    public void setValue(Object value) {
        this.value = value;
    }
}
